#include "MistakeBook.h"
#include <QDateTime>
#include <QScrollBar>

// ==================== MistakeDetailPage ====================

MistakeDetailPage::MistakeDetailPage(MistakeItem* item, QWidget* parent)
    : QWidget(parent), m_item(item)
{
    initUI();
    loadData();
}

void MistakeDetailPage::initUI()
{
    QVBoxLayout* mainLayout = new QVBoxLayout(this);

    // 标题
    QHBoxLayout* titleLayout = new QHBoxLayout();
    titleLayout->addWidget(new QLabel("标题:"));
    m_titleEdit = new QLineEdit();
    m_titleEdit->setPlaceholderText("输入错题标题...");
    titleLayout->addWidget(m_titleEdit);
    mainLayout->addLayout(titleLayout);

    // 描述
    mainLayout->addWidget(new QLabel("问题描述:"));
    m_descEdit = new QTextEdit();
    m_descEdit->setPlaceholderText("详细描述遇到的问题...");
    m_descEdit->setMaximumHeight(120);
    mainLayout->addWidget(m_descEdit);

    // 解决步骤
    QHBoxLayout* stepsHeaderLayout = new QHBoxLayout();
    stepsHeaderLayout->addWidget(new QLabel("解决步骤:"));
    stepsHeaderLayout->addStretch();

    QPushButton* addStepBtn = new QPushButton("添加步骤");
    QPushButton* removeStepBtn = new QPushButton("删除最后一步");
    QPushButton* moveUpBtn = new QPushButton("上移");
    QPushButton* moveDownBtn = new QPushButton("下移");

    stepsHeaderLayout->addWidget(addStepBtn);
    stepsHeaderLayout->addWidget(removeStepBtn);
    stepsHeaderLayout->addWidget(moveUpBtn);
    stepsHeaderLayout->addWidget(moveDownBtn);

    mainLayout->addLayout(stepsHeaderLayout);

    // 步骤容器
    QScrollArea* scrollArea = new QScrollArea();
    scrollArea->setWidgetResizable(true);
    QWidget* stepsWidget = new QWidget();
    m_stepsLayout = new QVBoxLayout(stepsWidget);
    scrollArea->setWidget(stepsWidget);
    mainLayout->addWidget(scrollArea);

    // 连接信号
    connect(addStepBtn, &QPushButton::clicked, this, &MistakeDetailPage::addStep);
    connect(removeStepBtn, &QPushButton::clicked, this, &MistakeDetailPage::removeStep);
    connect(moveUpBtn, &QPushButton::clicked, this, &MistakeDetailPage::moveStepUp);
    connect(moveDownBtn, &QPushButton::clicked, this, &MistakeDetailPage::moveStepDown);

    // 自动保存
    connect(m_titleEdit, &QLineEdit::textChanged, this, &MistakeDetailPage::saveData);
    connect(m_descEdit, &QTextEdit::textChanged, this, &MistakeDetailPage::saveData);
}

void MistakeDetailPage::loadData()
{
    if (!m_item) return;

    m_titleEdit->setText(m_item->title);
    m_descEdit->setText(m_item->description);

    // 加载步骤
    for (int i = 0; i < m_item->steps.size(); ++i) {
        addStep();
        m_stepEdits[i]->setText(m_item->steps[i].toString());
    }
}

void MistakeDetailPage::saveData()
{
    if (!m_item) return;

    m_item->title = m_titleEdit->text();
    m_item->description = m_descEdit->toPlainText();

    // 保存步骤
    m_item->steps = QJsonArray();
    for (int i = 0; i < m_stepEdits.size(); ++i) {
        m_item->steps.append(m_stepEdits[i]->toPlainText());
    }
}

void MistakeDetailPage::addStep()
{
    int stepNumber = m_stepEdits.size() + 1;

    QHBoxLayout* stepLayout = new QHBoxLayout();
    QLabel* stepLabel = new QLabel(QString("%1.").arg(stepNumber));
    stepLabel->setMinimumWidth(30);

    QTextEdit* stepEdit = new QTextEdit();
    stepEdit->setMaximumHeight(80);
    stepEdit->setPlaceholderText(QString("步骤 %1 的具体操作...").arg(stepNumber));

    stepLayout->addWidget(stepLabel);
    stepLayout->addWidget(stepEdit);

    m_stepsLayout->addLayout(stepLayout);
    m_stepLayouts.append(stepLayout);
    m_stepEdits.append(stepEdit);

    // 连接自动保存
    connect(stepEdit, &QTextEdit::textChanged, this, &MistakeDetailPage::saveData);

    saveData();
}

void MistakeDetailPage::removeStep()
{
    if (m_stepLayouts.isEmpty()) return;

    QHBoxLayout* layout = m_stepLayouts.takeLast();
    QTextEdit* edit = m_stepEdits.takeLast();

    // 清理布局
    QLayoutItem* item;
    while ((item = layout->takeAt(0)) != nullptr) {
        if (item->widget()) {
            item->widget()->deleteLater();
        }
        delete item;
    }
    delete layout;

    edit->deleteLater();
    saveData();
}

void MistakeDetailPage::moveStepUp()
{
    // 实现步骤上移逻辑
    // 这里需要处理UI和数据的重新排序
}

void MistakeDetailPage::moveStepDown()
{
    // 实现步骤下移逻辑
}

// ==================== MistakeBook ====================

MistakeBook::MistakeBook(QWidget* parent)
    : QWidget(parent)
{
    initUI();
    initCategories();
    loadMistakes();
}

void MistakeBook::initUI()
{
    QHBoxLayout* mainLayout = new QHBoxLayout(this);

    // 左侧：错题列表
    QVBoxLayout* leftLayout = new QVBoxLayout();
    leftLayout->setContentsMargins(0, 0, 0, 0);

    // 分类筛选
    QHBoxLayout* filterLayout = new QHBoxLayout();
    filterLayout->addWidget(new QLabel("分类:"));
    m_categoryCombo = new QComboBox();
    filterLayout->addWidget(m_categoryCombo);
    filterLayout->addStretch();
    leftLayout->addLayout(filterLayout);

    // 错题列表
    m_mistakeList = new QListWidget();
    leftLayout->addWidget(m_mistakeList);

    // 操作按钮
    QHBoxLayout* buttonLayout = new QHBoxLayout();
    m_addButton = new QPushButton("添加错题");
    m_deleteButton = new QPushButton("删除错题");
    m_exportButton = new QPushButton("导出TXT");
    m_importButton = new QPushButton("导入数据");

    buttonLayout->addWidget(m_addButton);
    buttonLayout->addWidget(m_deleteButton);
    buttonLayout->addWidget(m_exportButton);
    buttonLayout->addWidget(m_importButton);

    leftLayout->addLayout(buttonLayout);

    // 右侧：内容区域
    m_contentStack = new QStackedWidget();
    m_emptyLabel = new QLabel("请选择一个错题查看详情");
    m_emptyLabel->setAlignment(Qt::AlignCenter);
    m_contentStack->addWidget(m_emptyLabel);

    // 添加到主布局
    mainLayout->addLayout(leftLayout, 1);
    mainLayout->addWidget(m_contentStack, 2);

    // 连接信号
    connect(m_addButton, &QPushButton::clicked, this, &MistakeBook::onAddMistake);
    connect(m_deleteButton, &QPushButton::clicked, this, &MistakeBook::onDeleteMistake);
    connect(m_mistakeList, &QListWidget::itemClicked, this, &MistakeBook::onMistakeSelected);
    connect(m_categoryCombo, &QComboBox::currentTextChanged, this, &MistakeBook::onCategoryChanged);
    connect(m_exportButton, &QPushButton::clicked, this, &MistakeBook::onExportTxt);
    connect(m_importButton, &QPushButton::clicked, this, &MistakeBook::onImportData);
}

void MistakeBook::initCategories()
{
    QStringList categories = {
        "投资理财", "工作技能", "人际关系", "时间管理",
        "创业经营", "学习成长", "健康生活", "其他"
    };

    m_categoryCombo->addItem("全部");
    m_categoryCombo->addItems(categories);
}

void MistakeBook::loadMistakes()
{
    // 这里可以从文件或数据库加载数据
    // 暂时添加一些示例数据
    if (m_mistakes.isEmpty()) {
        MistakeItem example1;
        example1.title = "没有及时止损的投资";
        example1.category = "投资理财";
        example1.description = "在股票下跌时过于乐观，没有及时止损导致更大损失";
        example1.date = QDateTime::currentDateTime().toString("yyyy-MM-dd");
        example1.steps = QJsonArray({
            "设定明确的止损点（例如下跌10%立即卖出）",
            "定期回顾投资组合，移除表现不佳的资产",
            "学习技术分析，识别趋势转折信号",
            "建立投资纪律，避免情绪化决策"
            });

        MistakeItem example2;
        example2.title = "错过重要的工作机会";
        example2.category = "工作技能";
        example2.description = "因为没有持续学习新技能，错过了高薪工作机会";
        example2.date = QDateTime::currentDateTime().toString("yyyy-MM-dd");
        example2.steps = QJsonArray({
            "制定季度学习计划，掌握市场需求技能",
            "参加行业培训和认证考试",
            "建立专业人脉网络",
            "定期更新简历和作品集"
            });

        m_mistakes.append(example1);
        m_mistakes.append(example2);
    }

    refreshMistakeList();
}

void MistakeBook::saveMistakes()
{
    // 这里可以保存到文件或数据库
    QJsonArray mistakesArray;
    for (const MistakeItem& item : m_mistakes) {
        QJsonObject obj;
        obj["title"] = item.title;
        obj["category"] = item.category;
        obj["description"] = item.description;
        obj["steps"] = item.steps;
        obj["date"] = item.date;
        mistakesArray.append(obj);
    }

    QJsonDocument doc(mistakesArray);
    // 保存到文件...
}

void MistakeBook::refreshMistakeList()
{
    m_mistakeList->clear();

    QString currentCategory = m_categoryCombo->currentText();

    for (int i = 0; i < m_mistakes.size(); ++i) {
        const MistakeItem& item = m_mistakes[i];

        if (currentCategory != "全部" && item.category != currentCategory) {
            continue;
        }

        QListWidgetItem* listItem = new QListWidgetItem();
        listItem->setText(QString("%1 [%2]").arg(item.title).arg(item.category));
        listItem->setData(Qt::UserRole, i); // 存储索引
        m_mistakeList->addItem(listItem);
    }
}

void MistakeBook::onAddMistake()
{
    MistakeItem newItem;
    newItem.title = "新的错题记录";
    newItem.category = m_categoryCombo->currentText() == "全部" ? "其他" : m_categoryCombo->currentText();
    newItem.date = QDateTime::currentDateTime().toString("yyyy-MM-dd");
    newItem.steps = QJsonArray({ "" });

    m_mistakes.append(newItem);
    refreshMistakeList();

    // 自动选中新添加的项
    if (m_mistakeList->count() > 0) {
        m_mistakeList->setCurrentRow(m_mistakeList->count() - 1);
    }
}

void MistakeBook::onDeleteMistake()
{
    QListWidgetItem* currentItem = m_mistakeList->currentItem();
    if (!currentItem) return;

    int index = currentItem->data(Qt::UserRole).toInt();
    if (index >= 0 && index < m_mistakes.size()) {
        int ret = QMessageBox::question(this, "确认删除",
            "确定要删除这个错题记录吗？",
            QMessageBox::Yes | QMessageBox::No);
        if (ret == QMessageBox::Yes) {
            m_mistakes.removeAt(index);
            refreshMistakeList();
            m_contentStack->setCurrentWidget(m_emptyLabel);
        }
    }
}

void MistakeBook::onMistakeSelected(QListWidgetItem* item)
{
    if (!item) return;

    int index = item->data(Qt::UserRole).toInt();
    showMistakeDetail(index);
}

void MistakeBook::showMistakeDetail(int index)
{
    if (index < 0 || index >= m_mistakes.size()) return;

    // 移除旧的详情页面（如果有）
    if (m_contentStack->count() > 1) {
        QWidget* oldWidget = m_contentStack->widget(1);
        m_contentStack->removeWidget(oldWidget);
        oldWidget->deleteLater();
    }

    // 创建新的详情页面
    MistakeDetailPage* detailPage = new MistakeDetailPage(&m_mistakes[index]);
    m_contentStack->addWidget(detailPage);
    m_contentStack->setCurrentWidget(detailPage);
}

void MistakeBook::onCategoryChanged(const QString& category)
{
    Q_UNUSED(category)
        refreshMistakeList();
}

void MistakeBook::onExportTxt()
{
    QString fileName = QFileDialog::getSaveFileName(this, "导出错题本",
        "错题记录.txt",
        "文本文件 (*.txt)");
    if (fileName.isEmpty()) return;

    QFile file(fileName);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QMessageBox::warning(this, "错误", "无法创建文件");
        return;
    }

    QTextStream out(&file);

    out << "=== 赚钱目标错题本 ===\n\n";

    for (const MistakeItem& item : m_mistakes) {
        out << "标题: " << item.title << "\n";
        out << "分类: " << item.category << "\n";
        out << "日期: " << item.date << "\n";
        out << "问题描述:\n" << item.description << "\n\n";
        out << "解决步骤:\n";

        for (int i = 0; i < item.steps.size(); ++i) {
            out << QString("%1. %2\n").arg(i + 1).arg(item.steps[i].toString());
        }

        out << "\n" << QString("-").repeated(50) << "\n\n";
    }

    file.close();
    QMessageBox::information(this, "成功", "错题本已导出到文件");
}

void MistakeBook::onImportData()
{
    // 实现导入功能
    QMessageBox::information(this, "提示", "导入功能待实现");
}
